<template>
  <div class="hazardous-vehicle-reservation bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-6">危化品车辆预约管理</h2>

    <!-- 搜索栏 -->
    <div class="bg-card text-card-foreground p-6 rounded-lg shadow-sm mb-6">

      <QueryForm :model="search" :formItems="formItems" @search="searchReservations" @reset="resetSearch" />
    </div>

    <!-- 操作按钮 -->
    <div class="mb-6">
      <div>
        <el-button type="primary" @click="openReservationDialog">预约</el-button>
        <el-button type="danger" @click="deleteSelected">删除</el-button>
        <el-button @click="openImportDialog">导入</el-button>
        <el-button @click="exportData(reservations, '危化品预约', selectedIds)">导出</el-button>
      </div>

    </div>

    <!-- 预约列表 -->

    <div class=" bg-card text-card-foreground my-6 rounded shadow-md">
      <el-table :data="displayedReservations" @selection-change="handleSelectionChange" style="width: 100%" ref="table"
        align="center" class="data-table" :header-cell-style="headerCellStyle" :row-key="rowKey">

        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="LICENSE_PLATE" label="车牌号码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="VEHICLE_TYPE" label="车辆类型" header-align="center" align="center"></el-table-column>
        <el-table-column prop="VEHICLE_COLOR" label="车牌颜色" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DRIVER_NAME" label="驾驶员姓名" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DRIVER_ID_NUMBER" label="证件号码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="ESCORT_NAME" label="押运员姓名" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DRIVING_LICENSE" label="行驶证" header-align="center" align="center">
          <template #default="scope">

            <span v-if="!scope.row.imgdata">暂无图片</span>
            <el-image v-else style="width: 100px; height: 100px" lazy :src="scope.row.imgdata" :zoom-rate="1.2"
              :max-scale="7" :min-scale="0.2" :initial-index="0" fit="cover" />
          </template>

        </el-table-column>
        <el-table-column prop="HAZARDOUS_MATERIAL_NAME" label="危化品名称" header-align="center"
          align="center"></el-table-column>
        <el-table-column prop="TRANSPORT_CODE" label="所属运输企业编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="SUBMISSION_TIME" label="提交时间" header-align="center" align="center">
          <template #default="scope">
            {{ dayjs(scope.row.SUBMISSION_TIME).format('YYYY-MM-DD HH:mm:ss') }}
          </template>

        </el-table-column>
        <el-table-column prop="RESERVATION_STATUS" label="预约状态" header-align="center" align="center">
          <template #default="scope">
            <div :class="getStatusClass(scope.row.RESERVATION_STATUS)">
              {{ getStatusText(scope.row.RESERVATION_STATUS) }}
            </div>

          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button v-if="getStatusText(scope.row.RESERVATION_STATUS) == '已提交'" type="primary" size="small"
              @click="editReservation(scope.row)" link>编辑</el-button>
            <el-button type="primary" size="small" @click="viewReservation(scope.row)" link>查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->

    <Pagination v-if="reservations.length" :tableData="reservations" @alltabledata="alltabledata" />




    <!-- 导入对话框 -->
    <el-dialog width="400px" class="dialog-from" v-model="isImportDialogOpen" title="导入" destroy-on-close align-center
      :before-close="closeImportDialog">
      <input type="file" @change="handleFileUpload" accept=".xlsx,.xls,.csv" class="mb-4" />
      <div class="flex justify-end space-x-2">
        <el-button @click="closeImportDialog">取消</el-button>
        <el-button type="primary" @click="importData">导入</el-button>
      </div>

    </el-dialog>
    <!-- 
    <teleport to="body">
      <div v-if="isImportDialogOpen" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
        <div class="bg-card p-6 rounded-lg shadow-lg w-full max-w-md">
          <h3 class="text-lg font-bold mb-4">导入预约数据</h3>
         
        </div>
      </div>
    </teleport> -->

    <!-- 查看详情对话框 -->
    <el-dialog class="dialog-from" v-model="isViewDialogOpen" title="预约详情" width="650" destroy-on-close align-center>

      <div class="tablename">
        <div
          style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
        </div>
        <span>基本信息</span>
      </div>
      <div class="grid grid-cols-3 gap-4">
        <div><strong>系统单号：</strong>{{ viewingReservation.SYSTEM_CODE }}</div>
        <div><strong>车牌号码：</strong>{{ viewingReservation.LICENSE_PLATE }}</div>
        <div><strong>车辆类型：</strong>{{ viewingReservation.VEHICLE_TYPE }}</div>
        <div><strong>车牌颜色：</strong>{{ viewingReservation.VEHICLE_COLOR }}</div>
        <div><strong>所属运输企业编码：</strong>{{ viewingReservation.TRANSPORT_CODE }}</div>
        <div><strong>危化品名称：</strong>{{ viewingReservation.HAZARDOUS_MATERIAL_NAME }}</div>
        <div><strong>危化品类别：</strong>{{ viewingReservation.HAZARDOUS_MATERIAL_TYPE }}</div>
        <div><strong>重量：</strong>{{ viewingReservation.WEIGHT }}</div>
        <div><strong>货运状态：</strong>{{ viewingReservation.TRANS_STATUS }}</div>
        <div><strong>前往企业：</strong>{{ viewingReservation.TRANSPORT_COMPANY }}</div>
        <div><strong>预计入园时间：</strong>{{ formatDateTime(viewingReservation.IN_AT) }}</div>
        <div><strong>预计出园时间：</strong>{{ formatDateTime(viewingReservation.EXIT_AT) }}</div>
        <div><strong>道路运输证号：</strong>{{ viewingReservation.ROAD_TRANSPORT_ROAD }}</div>
      </div>
      <div class="tablename">
        <div
          style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
        </div>
        <span>驾驶员信息</span>
      </div>
      <div class="grid grid-cols-3 gap-4">
        <div><strong>驾驶员姓名：</strong>{{ viewingReservation.DRIVER_NAME }}</div>
        <div><strong>证件号码：</strong>{{ viewingReservation.DRIVER_ID_NUMBER }}</div>
        <div><strong>联系方式：</strong>{{ viewingReservation.DRIVER_PHONE }}</div>
        <div><strong>押运员姓名：</strong>{{ viewingReservation.ESCORT_NAME }}</div>
        <div><strong>证件号码：</strong>{{ viewingReservation.ESCORT_ID_NUMBER }}</div>
        <div><strong>联系方式：</strong>{{ viewingReservation.ESCORT_PHONE }}</div>
        <div><strong>行驶证：</strong>
          <div v-if="viewingReservation.DRIVING_LICENSE == null">
            {{ viewingReservation.DRIVING_LICENSE }}
          </div>

          <span v-else v-for="item in imgdata" :key="item">
            <el-image style="width: 100px; height: 100px" lazy :src="item" :zoom-rate="1.2" :max-scale="7"
              :min-scale="0.2" :initial-index="0" fit="cover" />
          </span>

        </div>
        <div><strong>有效期起：</strong>{{ formatDateTime(viewingReservation.LEN_START_DATE) }}</div>
        <div><strong>有效期止：</strong>{{ formatDateTime(viewingReservation.LEN_START_END) }}</div>
        <div><strong>是否有效：</strong>{{ viewingReservation.WHETHER_LEN }}</div>
      </div>

      <div class="tablename">
        <div
          style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
        </div>
        <span>其他信息</span>
      </div>
      <div><strong>备注：</strong>{{ viewingReservation.STAMP }}</div>
      <div class="mt-6 flex justify-end space-x-2">
        <el-button @click="closeViewDialog">关闭</el-button>
      </div>


    </el-dialog>

    <!--  -->
    <el-dialog class="dialog-from" v-model="isReservationDialogOpen"
      :title="isEditing ? '危险化学品运输车辆编辑预约' : '危险化学品运输车辆新增预约'" width="650" destroy-on-close align-center>
      <form>
        <!-- 基本信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>基本信息</span>
          </div>
          <div class="grid grid-cols-3 gap-4">

            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">车牌号码：</label>
              <el-input type="text" id="licensePlate" v-model="reservationForm.LICENSE_PLATE" required class="input" />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">车辆类型：</label>
              <el-select v-model="reservationForm.VEHICLE_TYPE" class="set-select" placeholder="请选择">
                <el-option label="液体罐车" value="液体罐车" />
              </el-select>
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">车牌颜色：</label>
              <el-select v-model="reservationForm.VEHICLE_COLOR" class="set-select" placeholder="请选择">
                <el-option label="黄色" value="黄色" />
                <el-option label="蓝色" value="蓝色" />
                <el-option label="绿色" value="绿色" />
              </el-select>
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">所属运输企业编码：</label>
              <el-input type="text" id="licensePlate" v-model="reservationForm.TRANSPORT_CODE" class="input" />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">危化品名称：</label>
              <el-select v-model="reservationForm.HAZARDOUS_MATERIAL_NAME" class="set-select" placeholder="请选择">
                <el-option label="氯化钠" value="氯化钠" />
              </el-select>
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">危化品类别：</label>
              <el-input type="text" id="licensePlate" v-model="reservationForm.HAZARDOUS_MATERIAL_TYPE" required
                class="input" />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">重量（kg）：</label>
              <el-input type="text" id="licensePlate" v-model="reservationForm.WEIGHT" required class="input" />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">货运状态：</label>
              <el-select v-model="reservationForm.TRANS_STATUS" class="set-select" placeholder="请选择">
                <el-option label="供货" value="供货" />
                <el-option label="提货" value="提货" />
              </el-select>
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">前往企业：</label>
              <el-input type="text" id="licensePlate" v-model="reservationForm.TRANSPORT_COMPANY" required
                class="input" />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">预计入园时间：</label>
              <input type="datetime-local" id="submissionTime" v-model="reservationForm.IN_AT" required
                class='clatime ' />
            </div>

            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">预计出园时间：</label>
              <input type="datetime-local" id="submissionTime" v-model="reservationForm.EXIT_AT" required
                class='clatime ' />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">道路运输证号：</label>
              <el-input type="text" id="licensePlate" v-model="reservationForm.ROAD_TRANSPORT_ROAD" required
                class="input" />
            </div>

          </div>
        </div>
        <!-- 驾驶员信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>驾驶员信息</span>
          </div>
          <div class="grid grid-cols-3 gap-4">
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">驾驶员姓名：</label>
              <el-input type="text" id="licensePlate" v-model="reservationForm.DRIVER_NAME" required class="input" />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">证件号码：</label>
              <el-input type="text" id="licensePlate" v-model="reservationForm.DRIVER_ID_NUMBER" required
                class="input" />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">联系方式：</label>
              <el-input type="text" id="licensePlate" v-model="reservationForm.DRIVER_PHONE" required class="input" />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">押运员姓名：</label>
              <el-input type="text" id="licensePlate" v-model="reservationForm.ESCORT_NAME" class="input" />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">证件号码：</label>
              <el-input type="text" id="licensePlate" v-model="reservationForm.ESCORT_ID_NUMBER" class="input" />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">联系方式：</label>
              <el-input type="text" id="licensePlate" v-model="reservationForm.ESCORT_PHONE" class="input" />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">行驶证：</label>
              <!-- <el-input type="text" id="licensePlate" v-model="reservationForm.DRIVING_LICENSE" required class="input" /> -->
              <div v-if="isEditing" style="margin:10px 0">
                <span v-for="item in imgdata" :key="item">
                  <el-image style="width: 100px; height: 100px" lazy :src="item" :zoom-rate="1.2" :max-scale="7"
                    :min-scale="0.2" :initial-index="0" fit="cover" />
                </span>
              </div>
              <input type="file" id="importFile" @change="handleRISK_HAS" class="mt-1 block w-full" />

            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">有效期起：</label>
              <input type="datetime-local" id="submissionTime" v-model="reservationForm.LEN_START_DATE" required
                class='clatime ' />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">有效期止：</label>
              <input type="datetime-local" id="submissionTime" v-model="reservationForm.LEN_START_END" required
                class='clatime ' />
            </div>
            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">是否有效：</label>
              <el-select v-model="reservationForm.WHETHER_LEN" class="set-select" placeholder="请选择">
                <el-option label="有效" value="有效" />
                <el-option label="无效" value="无效" />
              </el-select>
            </div>

          </div>
        </div>
        <!-- 其他信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>其他信息</span>
          </div>
          <div>
            <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">备注：</label>
            <el-input type="text" id="licensePlate" v-model="reservationForm.STAMP" required class="input" />
          </div>
        </div>
        <div class="mt-6 flex justify-end space-x-2">
          <el-button @click="closeReservationDialog">取消</el-button>
          <el-button @click="submitReservation" type="primary">提交</el-button>
        </div>
      </form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
import { dayjs } from 'element-plus'
const { proxy } = getCurrentInstance()
const apiBaseUrl = computed(() => proxy.$currentUrl + '/api/hazardous-vehicle-reservations')
import { exportData, checkval } from '#/utils/exportfile.js'
// 状态变量
const reservations = ref([])
const search = ref({ LICENSE_PLATE: '', DRIVER_NAME: '', RESERVATION_STATUS: '' })
const formItems = ref([
  {
    label: '车牌号码：',
    model: 'LICENSE_PLATE',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '驾驶员姓名：',
    model: 'DRIVER_NAME',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '预约状态：',
    model: 'RESERVATION_STATUS',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '已提交', value: 'pending' },
      { label: '未通过', value: 'rejected' },
      { label: '已通过', value: 'approved' },
    ],
  },
])
const imgdata = ref([])
const selectAll = ref(false)
const tableheard = ['序号', '车牌号码', '车辆类型', '车牌颜色', '驾驶员姓名', '证件号码', '押运员姓名', '行驶证', '危化品名称', '所属运输企业编码', '提交时间', '预约状态']
const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
const table = ref()
const rowKey = (row) => row.ID // 设置行的唯一标识
const selectedIds = ref([])
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
const handleRISK_HAS = (event) => {
  reservationForm.value.files = []
  const files = Array.from(event.target.files)
  reservationForm.value.files = [files[0]]

}
const isReservationDialogOpen = ref(false)
const isImportDialogOpen = ref(false)
const isEditing = ref(false)
const reservationForm = ref({
  LICENSE_PLATE: '', //车牌号码：
  VEHICLE_TYPE: '', //车辆类型：
  VEHICLE_COLOR: '', //车牌颜色：
  TRANSPORT_CODE: '', //所属运输企业编码：
  HAZARDOUS_MATERIAL_NAME: '', //危化品名称：
  HAZARDOUS_MATERIAL_TYPE: '', //危化品类别：
  WEIGHT: '', //重量：
  TRANS_STATUS: '', //货运状态：
  TRANSPORT_COMPANY: '', //前往企业：
  IN_AT: '', //预计入园时间：
  EXIT_AT: '', //预计出园时间：
  ROAD_TRANSPORT_ROAD: '', //道路运输证号：

  DRIVER_NAME: '', //驾驶员姓名：
  DRIVER_ID_NUMBER: '', //证件号码：
  DRIVER_PHONE: '', //联系方式：
  ESCORT_NAME: '', //押运员姓名：
  ESCORT_ID_NUMBER: '', //证件号码：
  ESCORT_PHONE: '', //联系方式：
  DRIVING_LICENSE: '', //行驶证：
  LEN_START_DATE: '', //有效期起：
  LEN_START_END: '', //有效期止：
  WHETHER_LEN: '', //是否有效：

  STAMP: '', //备注：
  files: []
})
const importFile = ref(null)
const isViewDialogOpen = ref(false)
const viewingReservation = ref({})

// 计算属性


const displayedReservations = ref([])
const alltabledata = (data) => {
  displayedReservations.value = data

}
// 方法
const searchReservations = async () => {
  displayedReservations.value = []
  try {
    // const response = await axios.get(`${apiBaseUrl.value}/search`, { params: search.value })
    // reservations.value = response.data.map(equipment => ({ ...equipment, selected: false }))

    const response = await axios.get(`${apiBaseUrl.value}/search`, { params: search.value })
    reservations.value = (await Promise.all(response.data.map(async (item) => {
      if (item.DRIVING_LICENSE != null && item.DRIVING_LICENSE != '') {
        const resimg = await axios.get(`${apiBaseUrl.value}/download/${item.DRIVING_LICENSE}`)
        return { ...item, checked: false, imgdata: resimg.data.url }
      } else {
        return { ...item, checked: false, imgdata: item.DRIVING_LICENSE }
      }
    })))



  } catch (error) {
    console.error('搜索预约失败:', error)
    // 处理错误
  }
}

const resetSearch = () => {
  search.value = { LICENSE_PLATE: '', DRIVER_NAME: '', RESERVATION_STATUS: '' }
  searchReservations()
}

const openReservationDialog = (reservation = null) => {

  isEditing.value = false
  isReservationDialogOpen.value = true
}



const closeReservationDialog = () => {
  isReservationDialogOpen.value = false
  reservationForm.value = {
    files: []
  }
}

const submitReservation = async () => {

  if (checkval([
    'LICENSE_PLATE',
    'VEHICLE_TYPE',
    'VEHICLE_COLOR',
    'HAZARDOUS_MATERIAL_NAME',
    'HAZARDOUS_MATERIAL_TYPE',
    'WEIGHT',
    'TRANS_STATUS',
    'TRANSPORT_COMPANY',
    'IN_AT',
    'EXIT_AT',
    'ROAD_TRANSPORT_ROAD',
    'DRIVER_NAME',
    'DRIVER_ID_NUMBER',
    'DRIVER_PHONE',
    'ESCORT_NAME',
    'ESCORT_ID_NUMBER',
    'ESCORT_PHONE',
    'DRIVING_LICENSE',
    'LEN_START_DATE',
    'LEN_START_END',
    'WHETHER_LEN',
  ], '危化品预约', reservationForm.value)) {
    return
  }


  if (!reservationForm.value.files) {
    alert('驾驶证不能为空')
    return
  }


  const formData = new FormData()
  for (const key in reservationForm.value) {
    if (key !== 'files') {
      formData.append(key, reservationForm.value[key])
    }
  }
  if (reservationForm.value?.files) {
    reservationForm.value.files.forEach((file, index) => {
      formData.append(`files[${index}]`, file)
    })
  }
  try {
    if (isEditing.value) {
      await axios.put(`${apiBaseUrl.value}/${reservationForm.value.ID}`, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      alert('预约更新成功')
    } else {
      await axios.post(apiBaseUrl.value, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      alert('预约创建成功')
    }
    closeReservationDialog()
    searchReservations()
  } catch (error) {
    console.error('提交预约失败:', error)
    alert('提交预约失败: ' + (error.response?.data?.message || error.message))
  }
}

const deleteReservation = async (ID) => {
  if (confirm('确定要删除这条预约吗？')) {
    try {
      await axios.delete(`${apiBaseUrl.value}/${ID}`)
      alert('删除成功')
      await searchReservations()
    } catch (error) {
      console.error('删除预约失败:', error)
      alert('删除预约失败: ' + (error.response?.data?.message || error.message))
    }
  }
}



const openImportDialog = () => {
  isImportDialogOpen.value = true
}

const closeImportDialog = () => {
  isImportDialogOpen.value = false
  importFile.value = null
}

const handleFileUpload = (event) => {
  // 处理文件上传
  importFile.value = event.target.files[0]

}

const importData = async (file) => {
  if (!importFile.value) {
    alert('请选择要导入的文件')
    return
  }
  const formData = new FormData()
  formData.append('file', importFile.value)
  try {
    const response = await axios.post(`${apiBaseUrl.value}/Plan/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    alert(response.data.message || '导入成功')
    closeImportDialog()
    await allsearch()
  } catch (error) {
    console.error('导入失败:', error)
    alert('导入失败: ' + (error.response?.data?.message || error.message))
  }
}

// const formatDateTime = (dateTime) => {
//   // console.log(new Date(dateTime).toLocaleString())
//   return new Date(dateTime).toLocaleString()
// }
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return null
  const date = dayjs(dateTimeString).format('YYYY-MM-DD HH:mm:ss')
  return date
}
const getStatusText = (status) => {
  const statusMap = {
    pending: '已提交',
    approved: '已通过',
    rejected: '未通过'
  }
  return statusMap[status] || status
}

const getStatusClass = (status) => {
  switch (status) {
    case 'pending':
      return 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-green-800'
    case 'approved':
      return 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-yellow-800'
    case 'rejected':
      return 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800'
    default:
      return 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800'
  }
}



const viewReservation = async (reservation) => {
  imgdata.value = []
  viewingReservation.value = { ...reservation }

  isViewDialogOpen.value = true
  if (reservation.DRIVING_LICENSE) {
    const response = await axios.get(`${apiBaseUrl.value}/download/${reservation.DRIVING_LICENSE}`)
    imgdata.value.push(response.data.url)
  }
}

const closeViewDialog = () => {
  isViewDialogOpen.value = false
  viewingReservation.value = {}
}

const editReservation = async (reservation) => {
  imgdata.value = []
  reservationForm.value = {
    ...reservation,
    files: []
  }

  reservationForm.value.IN_AT = formatDateTime(reservation.IN_AT) //预计入园时间：
  reservationForm.value.EXIT_AT = formatDateTime(reservation.EXIT_AT) //预计出园时间：
  reservationForm.value.LEN_START_DATE = formatDateTime(reservation.LEN_START_DATE) //有效期起：
  reservationForm.value.LEN_START_END = formatDateTime(reservation.LEN_START_END) //有效期止：
  isEditing.value = true
  isReservationDialogOpen.value = true
  if (reservation.DRIVING_LICENSE) {
    const response = await axios.get(`${apiBaseUrl.value}/download/${reservation.DRIVING_LICENSE}`)
    imgdata.value.push(response.data.url)
  }
}
//
const toggleSelectAll = () => {
  reservations.value.forEach(equipment => equipment.selected = selectAll.value)
}
//
const deleteSelected = async () => {
  const selectedItems = reservations.value.filter(app => app.selected)

  if (selectedItems.length === 0) {
    alert('请至少选择一条记录进行删除')
    return
  }

  if (!confirm(`确定要删除选中的 ${selectedItems.length} 条记录吗？`)) {
    return
  }

  try {
    const deletePromises = selectedItems.map(item =>
      axios.delete(`${apiBaseUrl.value}/${item.ID}`)
    )

    await Promise.all(deletePromises)
    alert('删除成功')
    await searchReservations()
    table.value.clearSelection()

    selectAll.value = false
  } catch (error) {
    console.error('删除记录失败:', error)
    alert('删除记录失败: ' + (error.response?.data?.message || error.message))
  }
}
// 生命周期钩子
onMounted(() => {
  searchReservations()
})
</script>

<style scoped>
.input {
  @apply block w-full rounded-md border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring;
}

.btn {
  @apply px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out;
}

.btn-primary {
  @apply bg-primary text-white hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-sm {
  @apply px-2 py-1 text-sm;
}

/* 可以添加一些过渡效果 */
.inline-flex {
  transition: all 0.3s ease;
}
</style>
<style lass="scss" scoped>
.tablename {
  display: flex;
  align-items: baseline;
  margin: 10px 0;
  font-weight: bold;
}
</style>
